package com.aitesting.component;

import com.aitesting.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

@Slf4j
@Component
@Aspect
public class BindingResultAspect {
    /**
     * 定义一个切点,名字叫 bindingResult()
     * execution(方法修饰符 返回类型 方法所属的包.类名.方法名称(方法参数)
     */
    @Pointcut("execution(public * com.aitesting.controller.*.*(..))")
    public void bindingResult() {

    }

    @Around("bindingResult()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取被切方法的所有参数
        Object[] args = joinPoint.getArgs();
        for(Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult result = (BindingResult) arg;
                if (result.hasErrors()) {
                    FieldError fieldError = result.getFieldError();
                    if (fieldError != null) {
                        log.error(fieldError.getDefaultMessage());
                        return CommonResult.failed(fieldError.getDefaultMessage());
                    }else {
                        log.error("参数错误");
                        return CommonResult.failed();
                    }
                }
            }
        }
        //继续执行被切的方法
        return joinPoint.proceed();
    }
}
